package com.meida.student.app.scholartyrant.handler;

import com.meida.common.base.entity.EntityMap;
import com.meida.common.enums.PayStatusEnum;
import com.meida.common.mybatis.interceptor.PageInterceptor;
import com.meida.common.mybatis.model.PageParams;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.security.OpenHelper;
import com.meida.module.bus.provider.utils.MyDateUtils;
import com.meida.module.pay.client.entity.PayBalance;
import com.meida.module.pay.client.entity.PayInfo;
import com.meida.module.pay.provider.service.PayBalanceService;
import com.meida.module.pay.provider.service.PayInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 消费记录列表
 */
@Component
public class UserPayInfoPageListHandler implements PageInterceptor<PayInfo> {

    @Autowired
    private PayInfoService payInfoService;

    @Autowired
    private PayBalanceService payBalanceService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Override
    public void prepare(CriteriaQuery<PayInfo> cq, PageParams pageParams, EntityMap params) {
        String queryMonth = params.get("queryMonth");
        cq.clear();
        Long userId = OpenHelper.getUserId();
        cq.select(PayInfo.class, "payInfoId", "orderTitle", "payStatus", "payDate", "payType", "orderAmount", "returnAmount");
        cq.eq(PayInfo.class, "userId", userId);
        cq.ge("DATE_FORMAT(payinfo.createTime,'%Y-%m')", queryMonth);
        cq.orderByDesc("payinfo.createTime");
    }

    @Override
    public void complete(CriteriaQuery<PayInfo> cq, List<EntityMap> result, EntityMap extra) {
        Long userId = OpenHelper.getUserId();
        //总支出
        BigDecimal totalPayAmount = payInfoService.sumPayStatus(userId, PayStatusEnum.PAY.getCode());
        extra.put("totalPayAmount", totalPayAmount);
        //总退款
        BigDecimal totalRefundAmount = payInfoService.sumPayStatus(userId, PayStatusEnum.refund.getCode());
        extra.put("totalRefundAmount", totalRefundAmount);
        //留币余额
        PayBalance payBalance = payBalanceService.addUserBalance(userId);
        extra.put("balanceAmount", payBalance.getBindAmount());
        String targetTimezone = httpServletRequest.getHeader("targetTimezone");
        result.forEach(entityMap -> {
            String payDate = entityMap.get("payDate");
            String newPayDate = MyDateUtils.convertTimezone(payDate, targetTimezone);
            entityMap.put("payDate", newPayDate);
        });
    }
}
